package com.maventools.utils;

import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
 * @BelongsProject: maventools
 * @BelongsPackage: com.maventools.config
 * @Author: Layila
 * @CreateTime: 2025-04-20  10:40
 * @Description: 文件处理工具类
 * @Version: 1.0
 * @Since:Java17
 */
@Component
public class FilesUtils {
    /**
     * @Descrption 解压
     * @param zipFilePath
     * @param desDirectory
     * @throws IOException
     */
    public void unzip(String zipFilePath, String desDirectory) throws IOException {
        Path destDir = Paths.get(desDirectory);
        if (!Files.exists(destDir)) {
            Files.createDirectories(destDir);
        }

        try (ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(Paths.get(zipFilePath)))) {
            ZipEntry zipEntry = zipInputStream.getNextEntry();
            while (zipEntry != null) {
                Path filePath = destDir.resolve(zipEntry.getName());
                if (zipEntry.isDirectory()) {
                    Files.createDirectories(filePath);
                } else {
                    Path parentDir = filePath.getParent();
                    if (parentDir != null && !Files.exists(parentDir)) {
                        Files.createDirectories(parentDir);
                    }
                    try {
                        Files.copy(zipInputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
                    } catch (IOException e) {
                        System.err.println("Error extracting " + filePath + ": " + e.getMessage());
                        throw e;
                    }
                }
                zipInputStream.closeEntry();
                zipEntry = zipInputStream.getNextEntry();
            }
        }
    }

    /**
     * @Descrption  通过URL下载主方法
     * @param urlStr
     * @param destination
     * @throws IOException
     */
    public void downloadFile(String urlStr, Path destination) throws IOException {
        URL url = new URL(urlStr);
        try (InputStream in = url.openStream()) {
            Files.copy(in, destination, StandardCopyOption.REPLACE_EXISTING);
        }
    }

    /**
     * @Descrption 根据版本初始化下载链接
     * @param baseUrl
     * @param version
     * @param isBinary
     * @return
     */
    public String generateDownloadUrl(String baseUrl, String version, boolean isBinary) {
        String type = isBinary ? "bin" : "src";
        String artifact = "apache-maven-" + version + "-" + type;
        String extension = "zip";
        return baseUrl + version +"/"+   artifact + "." + extension;
    }

//    https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.2.3/apache-maven-3.2.3-src.zip
}
